<template>
	<view class="container">
		<!-- 头部导航 -->
		<view class="header">
			<view class="header-left" @click="navigateBack">
				<text class="iconfont icon-arrow-left"></text>
			</view>
			<view class="header-title">发布闲置</view>
			<view class="header-right" @click="publishItem">
				<text class="publish-btn">发布</text>
			</view>
		</view>

		<!-- 表单内容区 -->
		<view class="form-container">
			<!-- 商品图片上传 -->
			<view class="form-item">
				<view class="form-label">商品图片</view>
				<view class="image-upload">
					<uni-file-picker ref="filePicker" :max-count="1" :auto-upload="false" @select="onImageSelect"
						@delete="onImageDelete">
						<view class="upload-btn" slot="uploadBtn">
							<text class="iconfont icon-add"></text>
							<text>添加图片</text>
						</view>
					</uni-file-picker>
				</view>
			</view>

			<!-- 商品标题 -->
			<view class="form-item">
				<view class="form-label">商品标题</view>
				<view class="form-input">
					<input type="text" placeholder="请输入商品标题" v-model="formData.title" maxlength="30" />
				</view>
			</view>

			<!-- 商品分类 -->
			<view class="form-item">
				<view class="form-label">商品分类</view>
				<view class="form-select" @click="openCategoryPicker">
					<text>{{ formData.category || '请选择分类' }}</text>
					<text class="iconfont icon-arrow-right"></text>
				</view>
			</view>

			<!-- 商品描述 -->
			<view class="form-item">
				<view class="form-label">商品描述</view>
				<view class="form-textarea">
					<textarea placeholder="请详细描述商品情况，如：购买时间、使用情况、功能是否正常等" v-model="formData.description" maxlength="500"
						@input="countWords" />
					<view class="word-count">{{ wordsCount }}/500</view>
				</view>
			</view>

			<!-- 价格信息 -->
			<view class="form-item price-group">
				<view class="form-label">价格信息</view>
				<view class="price-item">
					<view class="price-label">原价</view>
					<view class="price-input">
						<text class="currency">¥</text>
						<input type="digit" placeholder="请输入原价" v-model="formData.originalPrice" />
					</view>
				</view>
				<view class="price-item">
					<view class="price-label">现价</view>
					<view class="price-input">
						<text class="currency">¥</text>
						<input type="digit" placeholder="请输入现价" v-model="formData.currentPrice" />
					</view>
				</view>
			</view>

			<!-- 交易方式 -->
			<view class="form-item">
				<view class="form-label">交易方式</view>
				<view class="trade-methods">
					<view class="method-item" :class="{ 'active': formData.tradeMethods.includes('offline') }"
						@click="toggleTradeMethod('offline')">
						<text class="iconfont"
							:class="formData.tradeMethods.includes('offline') ? 'icon-check' : 'icon-uncheck'"></text>
						<text>同城自提</text>
					</view>
				</view>
			</view>

			<!-- 商品状态 -->
			<view class="form-item">
				<view class="form-label">商品状态</view>
				<view class="condition-group">
					<view class="condition-item" :class="{ 'active': formData.condition === 'new' }"
						@click="setCondition('new')">
						<text>全新</text>
					</view>
					<view class="condition-item" :class="{ 'active': formData.condition === 'almostNew' }"
						@click="setCondition('almostNew')">
						<text>几乎全新</text>
					</view>
					<view class="condition-item" :class="{ 'active': formData.condition === 'good' }"
						@click="setCondition('good')">
						<text>有轻微使用痕迹</text>
					</view>
					<view class="condition-item" :class="{ 'active': formData.condition === 'normal' }"
						@click="setCondition('normal')">
						<text>有明显使用痕迹</text>
					</view>
				</view>
			</view>

			<!-- 联系电话 -->
			<view class="form-item">
				<view class="form-label">联系电话</view>
				<view class="form-input">
					<input type="tel" placeholder="请输入联系电话" v-model="formData.phone" />
				</view>
			</view>

			<!-- 地理位置 -->
			<view class="form-item">
				<view class="form-label">所在地区</view>
				<view class="form-select" @click="getLocation">
					<text>{{ formData.location || '点击获取当前位置' }}</text>
					<text class="iconfont icon-arrow-right"></text>
				</view>
			</view>

			<!-- 更多设置 -->
			<!-- <view class="form-item">
				<view class="form-label">更多设置</view>
				<view class="more-settings">
					<view class="setting-item">
						<text>接受议价</text>
						<switch color="#ff4400" v-model="formData.allowBargain" />
					</view>
					<view class="setting-item">
						<text>包邮</text>
						<switch color="#ff4400" v-model="formData.freeShipping" />
					</view>
				</view>
			</view> -->
		</view>

		<!-- 底部协议 -->
		<!-- <view class="agreement">
			<checkbox-group @change="onAgreementChange">
				<label>
					<checkbox :checked="isAgreed" color="#ff4400" />
					<text>我已阅读并同意</text>
					<text class="agreement-link">《二手交易平台服务协议》</text>
					<text>和</text>
					<text class="agreement-link">《隐私政策》</text>
				</label>
			</checkbox-group>
		</view> -->
	</view>
</template>

<script>
	import {
		publishGoods,
		getGoodsCategories,
		goodsUpload
	} from '@/api/goods'
	import upload from '@/utils/upload'
	export default {
		data() {
			return {
				formData: {
					title: '',
					category: '',
					categoryId: '',
					description: '',
					originalPrice: '',
					currentPrice: '',
					tradeMethods: [],
					condition: 'new',
					phone: '',
					location: '香川县高松市',
					allowBargain: false,
					freeShipping: false,
					images: []
				},
				wordsCount: 0,
				isAgreed: false,
				categoryList: [],
				uploadImages: [],
			}
		},
		async mounted() {
			await this.loadCategories();
		},
		methods: {
			async loadCategories() {
				try {
					const res = await getGoodsCategories();
					this.categories = res.data.rows || [];
				} catch (error) {
					this.$modal.showToast('加载分类失败');
				}
			},
			navigateBack() {
				uni.navigateBack();
			},
			onImageSelect(e) {
				this.uploadImages = this.uploadImages.concat(e.tempFiles[0]);
			},
			onImageDelete(e) {
				this.uploadImages.splice(e.index, 1);
			},
			async uploadImagesServer() {
				const uploadPromises = this.uploadImages.map(uploadImage => {
					return goodsUpload(uploadImage)
				});
				const results = await Promise.all(uploadPromises);
				debugger
				return results.map(res => res.url);
			},

			// 监听图片删除
			onImageDelete(e) {
				this.formData.images = this.formData.images.filter((item, index) => index !== e.index)
			},

			// 打开分类选择器
			openCategoryPicker() {
				uni.showActionSheet({
					itemList: this.categories.map(item => item.name),
					success: (res) => {
						this.formData.category = this.categories[res.tapIndex].name
						this.formData.categoryId = this.categories[res.tapIndex].id
					}
				})
			},

			// 计算字数
			countWords(e) {
				this.wordsCount = e.detail.value.length
			},

			// 切换交易方式
			toggleTradeMethod(method) {
				const index = this.formData.tradeMethods.indexOf(method)
				if (index > -1) {
					this.formData.tradeMethods.splice(index, 1)
				} else {
					this.formData.tradeMethods.push(method)
				}
			},

			// 设置商品状态
			setCondition(condition) {
				this.formData.condition = condition
			},

			// 获取地理位置
			getLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						uni.reverseGeocoder({
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							success: (geoRes) => {
								this.formData.location = geoRes.address
							},
							fail: (err) => {
								uni.showToast({
									title: '获取位置失败，请手动输入',
									icon: 'none'
								})
							}
						})
					},
					fail: (err) => {
						debugger
						uni.showToast({
							title: '请允许获取位置权限',
							icon: 'none'
						})
					}
				})
				uni.request({
				  url: 'http://ip-api.com/json',
				  method: 'GET',
				  success: function (res) {
				    console.log('IP定位结果：', res.data); // 包含国家、城市等信息
				  }
				});
			},

			// 协议勾选变化
			onAgreementChange(e) {
				this.isAgreed = e.detail.value.length > 0
			},

			async publishItem() {
				// 表单验证
				if (!this.formData.title) {
					return this.$modal.showToast('请输入商品标题');
				}
				if (!this.formData.category) {
					return this.$modal.showToast('请选择商品分类');
				}
				if (!this.formData.currentPrice) {
					return this.$modal.showToast('请输入商品价格');
				}
				if (this.uploadImages.length === 0) {
					return this.$modal.showToast('请上传商品图片');
				}

				try {
					// 上传图片
					const imageUrls = await this.uploadImagesServer();

					// 构建提交数据
					const submitData = {
						title: this.formData.title,
						categoryId: this.formData.categoryId,
						description: this.formData.description,
						// originalPrice: this.formData.originalPrice,
						price: this.formData.currentPrice,
						// condition: this.formData.condition,
						contactInfo: this.formData.phone,
						location: this.formData.location,
						// allowBargain: this.formData.allowBargain,
						// freeShipping: this.formData.freeShipping,
						images: JSON.stringify(imageUrls)
					};

					// 提交商品信息
					await publishGoods(submitData);
					this.$modal.showToast('发布成功');
					uni.navigateBack();
				} catch (error) {
					this.$modal.showToast('发布失败，请重试');
					console.error('发布失败:', error);
				}
			},

			// 表单验证
			validateForm() {
				if (!this.formData.title) {
					uni.showToast({
						title: '请填写商品标题',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.category) {
					uni.showToast({
						title: '请选择商品分类',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.description || this.formData.description.length < 10) {
					uni.showToast({
						title: '商品描述至少10个字',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.currentPrice) {
					uni.showToast({
						title: '请填写现价',
						icon: 'none'
					})
					return false
				}

				if (this.formData.originalPrice && parseFloat(this.formData.currentPrice) > parseFloat(this.formData
						.originalPrice)) {
					uni.showToast({
						title: '现价不能高于原价',
						icon: 'none'
					})
					return false
				}

				if (this.formData.tradeMethods.length === 0) {
					uni.showToast({
						title: '请至少选择一种交易方式',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.phone || !/^1[3-9]\d{9}$/.test(this.formData.phone)) {
					uni.showToast({
						title: '请填写正确的手机号',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.location) {
					uni.showToast({
						title: '请获取所在地区',
						icon: 'none'
					})
					return false
				}

				if (!this.isAgreed) {
					uni.showToast({
						title: '请同意相关协议',
						icon: 'none'
					})
					return false
				}

				return true
			}
		}
	}
</script>

<style>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 44px;
		padding: 0 15px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.header-left,
	.header-right {
		width: 40px;
		text-align: center;
	}

	.header-title {
		font-size: 18px;
		font-weight: bold;
	}

	.publish-btn {
		color: #ff4400;
		font-size: 16px;
	}

	.form-container {
		margin-top: 10px;
		background-color: #fff;
	}

	.form-item {
		padding: 15px;
		border-bottom: 1px solid #eee;
	}

	.form-label {
		font-size: 15px;
		color: #333;
		margin-bottom: 10px;
	}

	.form-input input,
	.form-textarea textarea {
		width: 100%;
		font-size: 14px;
		color: #666;
	}

	.form-textarea textarea {
		min-height: 100px;
	}

	.word-count {
		text-align: right;
		font-size: 12px;
		color: #999;
		margin-top: 5px;
	}

	.form-select {
		display: flex;
		align-items: center;
		justify-content: space-between;
		color: #666;
		font-size: 14px;
	}

	.image-upload {
		display: flex;
		flex-wrap: wrap;
	}

	.upload-btn {
		width: 70px;
		height: 70px;
		border: 1px dashed #ddd;
		border-radius: 4px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 12px;
	}

	.upload-btn .iconfont {
		font-size: 20px;
		margin-bottom: 3px;
	}

	.price-group {
		padding-bottom: 0;
	}

	.price-item {
		display: flex;
		align-items: center;
		padding-bottom: 15px;
	}

	.price-label {
		width: 60px;
		font-size: 15px;
		color: #333;
	}

	.price-input {
		flex: 1;
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding-bottom: 5px;
	}

	.currency {
		margin-right: 5px;
		color: #666;
	}

	.trade-methods {
		display: flex;
	}

	.method-item {
		display: flex;
		align-items: center;
		margin-right: 20px;
		color: #666;
		font-size: 14px;
	}

	.method-item.active {
		color: #ff4400;
	}

	.condition-group {
		display: flex;
		flex-wrap: wrap;
	}

	.condition-item {
		padding: 8px 12px;
		margin-right: 10px;
		margin-bottom: 10px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 13px;
		color: #666;
	}

	.condition-item.active {
		border-color: #ff4400;
		background-color: rgba(255, 68, 0, 0.05);
		color: #ff4400;
	}

	.more-settings {
		display: flex;
		flex-direction: column;
	}

	.setting-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 0;
		border-bottom: 1px solid #eee;
	}

	.setting-item:last-child {
		border-bottom: none;
	}

	.setting-item text {
		font-size: 14px;
		color: #666;
	}

	.agreement {
		padding: 15px;
		font-size: 12px;
		color: #999;
	}

	.agreement-link {
		color: #ff4400;
	}
</style>